// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // my_material:cc.Material,
        my_effect:cc.EffectAsset,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.material = null;
    },

    start () {
        if (CC_EDITOR) {
            setTimeout(() => {
                this.applyEffect();
            }, 1000);
        } else {
            this.applyEffect();
        }
    },

    applyEffect() {
        cc.log('shaderComp applyEffect called!');
        // 获取精灵组件
        let sprite = this.node.getComponent(cc.Sprite);
        if (!sprite) {
            return;
        }

        let effectAsset = this.my_effect;

        // 实例化一个材质对象
        let material = new cc.Material();

        // 在材质对象上开启USE_TEXTURE定义
        let defineUserTexture = !!effectAsset.shaders.find(shader => shader.defines.find(def => def.name === 'USE_TEXTURE'));
        if (defineUserTexture) {
            material.define('USE_TEXTURE', true);
        }

        // 为材质设置effect，也就是绑定Shader
        material.effectAsset = effectAsset;
        material.name = effectAsset.name;

        // 将材质绑定到精灵组件上，精灵可以绑定多个材质
        // 这里我们替换0号默认材质
        sprite.setMaterial(0, material);

        // 从精灵组件上获取材质，这步很重要，不然没效果
        this.material = sprite.getMaterial(0);

        // this.props.forEach(item => item.key && this.material.setProperty(item.key, item.value || 0));
    }

    // update (dt) {},
});
